<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author laz
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <a-button type="default" @click="handleExport()">
          <Icon icon="ant-design:download-outlined" /> {{ t('导出') }}
        </a-button>
        <a-button type="default" @click="handleImport()">
          <Icon icon="ant-design:upload-outlined" /> {{ t('导入') }}
        </a-button>
        <a-button type="primary" @click="handleForm({})" v-auth="'information:dailySigns:edit'">
          <Icon icon="fluent:add-12-filled" /> {{ t('新增') }}
        </a-button>
        <a-button type="default" @click="handlePullClick" :disabled="isPulling">
          <Icon icon="ant-design:pull-request-outlined" /> {{ t('拉取') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ tid: record.tid })">
          {{ record.createTime }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" :phone="phone" />
    <FormImport @register="registerImportModal" @success="handleSuccess" />

    <!-- 全屏加载蒙层 -->
    <div v-if="showLoading" class="loading-overlay">
      <div class="loading-content">
        <Spin tip="正在获取数据，请稍后..." size="large" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup name="ViewsInformationDailySignsList">
  import { unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { dailySignsDelete, dailySignsListData } from '/@/api/information/dailySigns';
  import { dailySignsSave, dailySignsInsert } from '/@/api/information/dailySigns';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import FormImport from './formImport.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { ref } from 'vue';
  import { getMappingId } from '/@/api/sys/desktopApi';
  import axios from 'axios';
  import { Modal } from 'ant-design-vue';
  import { Spin } from 'ant-design-vue';

  // 获取用户
  const currentUser = useUserStore().getUserInfo;
  const phone = currentUser.loginCode;
  const userId = currentUser.userCode;
  const { t } = useI18n('information.dailySigns');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const mappingId = ref({});

  // 新增状态变量
  const isPulling = ref(false); // 控制按钮禁用状态
  const showLoading = ref(false); // 控制全屏加载蒙层显示

  const getTitle = {
    icon: meta.icon || 'ant-design:book-outlined',
    value: meta.title || t('日常体征管理'),
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('上报时间'),
        field: 'createTime',
        component: 'DatePicker',
        componentProps: {
          format: 'YYYY-MM-DD',
          // format: 'YYYY-MM-DD HH:mm',
          // showTime: { format: 'HH:mm' },
        },
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('上报时间'),
      dataIndex: 'createTime',
      key: 'a.create_time',
      sorter: true,
      width: 230,
      align: 'center',
      slot: 'firstColumn',
    },
    {
      title: t('体重 (kg)'),
      dataIndex: 'weight',
      key: 'a.weight',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('心率 (次/分)'),
      dataIndex: 'heartRate',
      key: 'a.heart_rate',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('呼吸频率 (次/分)'),
      dataIndex: 'breathe',
      key: 'a.breathe',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('收缩压 (mmHg)'),
      dataIndex: 'systolicPressure',
      key: 'a.systolic_pressure',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('舒张压 (mmHg)'),
      dataIndex: 'diastolicPressure',
      key: 'a.diastolic_pressure',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('血糖 (mmol/L)'),
      dataIndex: 'bloodSugar',
      key: 'a.blood_sugar',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('体温 (℃)'),
      dataIndex: 'temperature',
      key: 'a.temperature',
      sorter: true,
      width: 130,
      align: 'center',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 160,
    actions: (record: Recordable) => [
      {
        icon: 'clarity:note-edit-line',
        title: t('编辑日常体征'),
        onClick: handleForm.bind(this, { tid: record.tid }),
        auth: 'information:dailySigns:edit',
      },
      {
        icon: 'ant-design:delete-outlined',
        color: 'error',
        title: t('删除日常体征'),
        popConfirm: {
          title: t('是否确认删除日常体征'),
          confirm: handleDelete.bind(this, record),
        },
        auth: 'information:dailySigns:edit',
      },
    ],
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, getForm }] = useTable({
    api: dailySignsListData,
    beforeFetch: (params) => {
      params = { ...params, phone: currentUser.loginCode };
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
  });

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  // 新增：按钮点击事件处理
  function handlePullClick() {
    // 禁用按钮
    isPulling.value = true;

    // 显示确认对话框
    Modal.confirm({
      title: '授权确认',
      content: '您将授权我们从中山医康养获取您的体征信息，是否继续？',
      onOk: async () => {
        // 用户确认后执行实际的拉取操作
        await handlePull();
      },
      onCancel: () => {
        // 用户取消后恢复按钮状态
        isPulling.value = false;
      },
    });
  }

  // 修改：实际的拉取数据逻辑
  async function handlePull() {
    try {
      // 显示全屏加载蒙层
      showLoading.value = true;

      // 获取映射ID
      mappingId.value = await getMappingId({
        phone: userId,
      });

      // 拉取数据
      const platformName = 'platformCId'; // 中山
      const id_1 = mappingId.value[platformName];

      if (!id_1) {
        showMessage('用户不在该平台');
        return;
      }

      const res = await axios.post(
        `http://snat.msuncloud-internal.com/pull-data-zhongshan`,
        { id: id_1 },
        {
          timeout: 150000,
          headers: {
            'Content-Type': 'application/json',
          },
        },
      );

      console.log('API 响应:', res.data);
      const reportList = JSON.parse(res.data.report);
      // const reportList = JSON.parse(
      //   '[\n    {\n        "weight": "75.2",\n        "heartRate": "72",\n        "breathe": "18",\n        "systolicPressure": "118",\n        "diastolicPressure": "78",\n        "temperature": "37.0",\n        "bloodSugar": "5.5",\n        "createTime": "2025-07-24 08:30:15"\n    },\n    {\n        "weight": "75.1",\n        "heartRate": "70",\n        "breathe": "17",\n        "systolicPressure": "120",\n        "diastolicPressure": "80",\n        "temperature": "37.0",\n        "bloodSugar": "5.3",\n        "createTime": "2025-07-25 08:32:05"\n    },\n    {\n        "weight": "75.3",\n        "heartRate": "75",\n        "breathe": "18",\n        "systolicPressure": "122",\n        "diastolicPressure": "79",\n        "temperature": "37.0",\n        "bloodSugar": "5.8",\n        "createTime": "2025-07-26 08:29:11"\n    },\n    {\n        "weight": "75.0",\n        "heartRate": "69",\n        "breathe": "17",\n        "systolicPressure": "119",\n        "diastolicPressure": "77",\n        "temperature": "37.0",\n        "bloodSugar": "5.4",\n        "createTime": "2025-07-27 08:31:00"\n    },\n    {\n        "weight": "74.9",\n        "heartRate": "71",\n        "breathe": "18",\n        "systolicPressure": "121",\n        "diastolicPressure": "81",\n        "temperature": "37.0",\n        "bloodSugar": "5.6",\n        "createTime": "2025-07-28 08:33:40"\n    },\n    {\n        "weight": "75.2",\n        "heartRate": "73",\n        "breathe": "17",\n        "systolicPressure": "117",\n        "diastolicPressure": "78",\n        "temperature": "37.0",\n        "bloodSugar": "5.7",\n        "createTime": "2025-07-29 08:30:50"\n    },\n    {\n        "weight": "75.4",\n        "heartRate": "70",\n        "breathe": "18",\n        "systolicPressure": "120",\n        "diastolicPressure": "80",\n        "temperature": "37.0",\n        "bloodSugar": "5.3",\n        "createTime": "2025-07-30 08:28:19"\n    },\n    {\n        "weight": "75.3",\n        "heartRate": "72",\n        "breathe": "17",\n        "systolicPressure": "122",\n        "diastolicPressure": "79",\n        "temperature": "37.0",\n        "bloodSugar": "5.5",\n        "createTime": "2025-07-31 08:34:02"\n    },\n    {\n        "weight": "75.1",\n        "heartRate": "68",\n        "breathe": "18",\n        "systolicPressure": "118",\n        "diastolicPressure": "76",\n        "temperature": "37.0",\n        "bloodSugar": "5.2",\n        "createTime": "2025-08-01 08:31:22"\n    },\n    {\n        "weight": "75.0",\n        "heartRate": "71",\n        "breathe": "17",\n        "systolicPressure": "119",\n        "diastolicPressure": "78",\n        "temperature": "37.0",\n        "bloodSugar": "5.4",\n        "createTime": "2025-08-02',
      // );
      // console.log('report:', report);
      reportList.forEach((report) => {
        report.phone = phone;
        report.userCode = phone;
      });
      // 去单位
      const ignoreList = ['createTime'];
      const dailySignsList = reportList.map((item) => stripUnitsFromObject(item, ignoreList));
      const finalDataList = dailySignsList.map(({ id, ...rest }) => rest);
      // const dailySignsList = reportList.map(stripUnitsFromObject);
      console.log('reportLlist123123123:', finalDataList);
      const resInsert = await dailySignsInsert(
        { isNewRecord: true, phone: phone, identification: '' },
        finalDataList,
      );

      // 成功反馈
      showMessage(resInsert.message || '数据拉取成功');
    } catch (e) {
      console.error('拉取失败:', e);
      // 失败反馈
      showMessage('数据拉取失败，请稍后重试');
    } finally {
      // 隐藏加载蒙层
      showLoading.value = false;
      // 恢复按钮状态
      isPulling.value = false;
      // 刷新表格
      reload();
    }
  }

  async function handleExport() {
    const { ctxAdminPath } = useGlobSetting();
    downloadByUrl({
      url: ctxAdminPath + '/information/dailySigns/exportData',
      params: getForm().getFieldsValue(),
    });
  }

  const [registerImportModal, { openModal: importModal }] = useModal();

  function handleImport() {
    importModal(true, {});
  }

  async function handleDelete(record: Recordable) {
    const params = { tid: record.tid };
    const res = await dailySignsDelete(params);
    showMessage(res.message);
    handleSuccess(record);
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }

  function stripUnitsFromObject(data, ignoreKeys: string[]) {
    const processedData = {};
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        const value = data[key];

        // 新增：检查当前 key 是否在忽略列表中
        // 如果是，则直接复制原始值，并跳过后续处理
        if (ignoreKeys.includes(key)) {
          processedData[key] = value;
          continue;
        }

        // 如果 key 不在忽略列表，则执行之前的逻辑
        if (typeof value === 'string') {
          const matchResult = value.match(/-?\d+(\.\d+)?/);
          if (matchResult) {
            processedData[key] = parseFloat(matchResult[0]);
          } else {
            processedData[key] = value;
          }
        } else {
          processedData[key] = value;
        }
      }
    }
    return processedData;
  }
</script>
<style scoped>
  /* 全屏加载蒙层样式 */
  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }

  .loading-content {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    text-align: center;
  }
</style>
